import dbConfig from '@/config/db.config'
import store from '@/store'
import { Idb } from './db/index'
import { FilesService, ArticleService } from './service'
import { ICache, Services } from './service'

const cache: ICache = {} as ICache

connectDb()
async function connectDb() {
  cache.db = new Idb(dbConfig)

  let flag = await cache.db.open()
  if (flag.every((e: any) => e !== false)) {
    // 初始化表对象
    cache.filesService = new FilesService(cache.db.db, 'files')
    cache.articleService = new ArticleService(cache.db.db, 'article')

    store.dispatch('db/connected')
    store.dispatch('db/getFiles')

    console.log('%c--------数据库启动成功', 'color: #0000ff', flag)
  } else {
    store.commit('db/disConnect')
    console.log('%c--------数据库启动失败', 'color: red', flag)
  }
}

export const services = new Services(cache)

export const addFile = services.addFile.bind(services)
export const getFile = services.getFile.bind(services)
export const getAllFiles = services.findAll.bind(services)
export const updataFile = services.updataFile.bind(services)
export const deleteFile = services.deleteFile.bind(services)
export const getArticle = services.getArticle.bind(services)
export const updateArticle = services.updateArticle.bind(services)
